package com.tanhua.server.service;

import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.server.exceptions.TanhuaException;
import com.tanhua.server.interceptors.UserHolder;
import com.tanhua.vo.CommentVo;
import com.tanhua.vo.ContactVo;
import com.tanhua.vo.MessageLikeVo;
import com.tanhua.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentsService {

    @Reference
    private CommentApi commentApi;
    @Reference
    private UserInfoApi userInfoApi;


    @Autowired
    private StringRedisTemplate redisTemplate;


    public ResponseEntity queryComments(String movementId, Integer page, Integer pagesize) {

//        Comment
        PageResult pageResult = commentApi.queryComments(movementId,page,pagesize);
        List<Comment> commentList = (List<Comment>) pageResult.getItems();
//        userInfo

        List<CommentVo> list = new ArrayList<>();
        for (Comment comment : commentList) {
            Long userId = comment.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);

            CommentVo commentVo = new CommentVo();
            BeanUtils.copyProperties(userInfo,commentVo);
            BeanUtils.copyProperties(comment,commentVo);

            commentVo.setId(comment.getId().toString());
            commentVo.setCreateDate(new SimpleDateFormat("HH:mm").format(new Date(comment.getCreated())));
//            commentVo.setHasLiked(); //TODO
            list.add(commentVo);

        }

        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);


    }

    public ResponseEntity saveComments(String movementId, String comment) {

        //发言冻结
        UserInfo user = userInfoApi.findById(UserHolder.getUserId());
        if (user != null){
            Long userId = user.getId();
            String userStatus = user.getUserStatus();
            //暂时
            String freezingRange = redisTemplate.boundValueOps("FREEZE_KEY_"+userId.toString()).get();
            //永久
            String freezingRangePlus = redisTemplate.boundValueOps("FREEZEFOREVER_KEY_"+userId.toString()).get();
            //冻结创建时间
            String freezeCreated = redisTemplate.boundValueOps("freezeCreated" + userId.toString()).get();
            //冻结时间
            String freezingTime = redisTemplate.boundValueOps("freezingTime" + userId.toString()).get();
            //逻辑判断被冻结（1 冻结登录，2 冻结发言，3 冻结发布动态）
            if (freezingRange == null) {
                userInfoApi.updateById(userId);
            }
            //逻辑判断 如果用户状态等于2（“封禁”）
            //因为不涉及登录，所有排除登录封禁
            if (StringUtils.equals(userStatus,"2")){
                if (StringUtils.equals(freezingRange,"2")){
                    //直接显示冻结时间
                    throw new TanhuaException(500,"你的账户于"+freezeCreated+"，限制发言为期："+freezingTime+"天");
                }else if (StringUtils.equals(freezingRangePlus,"forever")){//或者为永久封禁
                    throw new TanhuaException(500,"被永久冻结");
                }
            }
        }

        Comment comment1 = new Comment();

        comment1.setUserId(UserHolder.getUserId());
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(2)  ;//1-动态点赞，2-动态评论，3-动态喜欢 4-视频点赞  5-视频评论  6-评论点赞
        comment1.setContent(comment);
        commentApi.saveComment(comment1);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity queryCommentsPeople(Integer page, Integer pagesize, int commentType) {

        PageResult pageResult =  commentApi.queryCommentsPeople(UserHolder.getUserId(),page,pagesize,commentType);
        List<Comment> commentList = (List<Comment>) pageResult.getItems();

        List<MessageLikeVo> list = new ArrayList<>();
        for (Comment comment : commentList) {
            Long userId = comment.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);
            MessageLikeVo messageLikeVo = new MessageLikeVo();
            messageLikeVo.setId(comment.getId().toString());
            messageLikeVo.setNickname(userInfo.getNickname());
            messageLikeVo.setAvatar(userInfo.getAvatar());
            messageLikeVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date(comment.getCreated()))); //2019-09-08 10:07
            list.add(messageLikeVo);
        }
        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);


    }

    @Reference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public ResponseEntity contacts(Long userId) {
//      1、两个人的关系写入到 friend表中
//        107   1
//            userId   friendId
//              1        107
//             107       1
        friendApi.save(UserHolder.getUserId(),userId);
//     2、注册两个人的好友关系到环信上
        huanXinTemplate.contactUsers(UserHolder.getUserId(),userId);

        return ResponseEntity.ok(null);

    }

    public ResponseEntity queryContacts(Integer page, Integer pagesize) {
//        从mongo分页查询 PageResult<Friend>
        PageResult pageResult = friendApi.queryContacts(UserHolder.getUserId(),page,pagesize);
        List<Friend> friendList = (List<Friend>) pageResult.getItems();

        List<ContactVo> list= new ArrayList<>();
        for (Friend friend : friendList) {
            Long friendId = friend.getFriendId();
            UserInfo userInfo = userInfoApi.findById(friendId);

            ContactVo contactVo = new ContactVo();

            BeanUtils.copyProperties(userInfo,contactVo);
            contactVo.setUserId(userInfo.getId().toString());

            list.add(contactVo);

        }

        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);
    }
}
